/*
	Copyright (c) 2011 Andrey O. Zbitnev (azbitnev@gmail.com)
	Licensed under the MIT License (LICENSE).

	$Id: ys.progressbar.js 8 2012-04-10 12:57:10Z azbitnev@gmail.com $

	version: 0.4pa
*/

(function ($) {

	// private vars
	var serial = 1, controls = []

	// class progressbar
	$.ys.progressbar = {

		set: function (selector, value, raiseEvent) {
			var ctx = $(selector)
			ctx.each(function () {
				var f = controls[$(this).data('ys-progressbar-id')]
				if (f) f(value, raiseEvent)
			})
		},

		get: function (selector) {
			return $(selector).data('ys-progressbar-value')
		},

		create: function (selector, options) {

			var defaults = {
				min: 0,
				max: 100,
				value: 0.0,
				text: true,
				duration: 'fast',
				easing: 'swing',
				onchange: function (val, $el) { }
			}

			var opts = $.extend(defaults, options);
			if (opts.min > opts.max) {
				var m = opts.min
				opts.min = opts.max
				opts.max = m
			}
			if (opts.value < opts.min) opts.value = opts.min
			if (opts.value > opts.max) opts.value = opts.max

			if (!$.ys.progressbar.installed) {
				var savedVal = $.fn.val
				$.fn.val = function (value) {
					var $sel = $(this)
					if ($sel.data('ys-progressbar-id'))
						return (value === undefined ? $.ys.progressbar.get($sel) : $.ys.progressbar.set($sel, value))
					return savedVal.apply(this, arguments)
				}
				$.ys.progressbar.installed = true
			}

			return $(selector).each(function(i, el) {

				var $el = $(el)
				var $fill = $('<div class="fill"></div>').css({
					width: '0px',
					height: '' + $el.outerHeight() + 'px'
				})

				$el.prepend($fill)

				function setValue(value, raiseEvent) {
					var w = $el.outerWidth()
					var fw = ((value - opts.min) * w) / (opts.max - opts.min)
					$fill.stop(true, true).animate({
						width: '' + fw + 'px'
					}, opts.duration, opts.easing)
					$el.data('ys-progressbar-value', value)
					if (raiseEvent === undefined || raiseEvent)
						opts.onchange(value, $el)
				}

				var id = (serial ++)
				controls[id] = setValue
				$el.data('ys-progressbar-id', id)

				var dataVal = $el.data('ys-progressbar-value')
				setValue(dataVal !== undefined ? dataVal : opts.value)
			})
		}
	}

})(jQuery);
